import 'dart:core';

import 'package:common/common.dart';
import 'package:get/get.dart';

import '../../../constants/app_storage_keys.dart';
import '../model/login_modle.dart';
import 'user.dart';

typedef UserInfoBlock = void Function(UserProfile user);

/// description

/// 用户相关的单例服务，保存了Token，UserProfile等信息
class UserService extends GetxService {
  static UserService get to => Get.find();

  UserService();

  //用户登录Token
  String? token;
  //用户是否已经登录 - 可变字段
  Rx<bool> haslogin = false.obs;
  //用户详情信息 - 可变字段
  Rx<UserProfile> userProfile = UserProfile(avatar: '').obs;

  //极光推送的 registrationId - 可变字段
  RxString registrationId = ''.obs;

  bool get hasToken => token?.isNotEmpty ?? false;
  bool get isLogin => haslogin.value;
  UserProfile get getUserProfile => userProfile.value;
  String get getRegistrationId => registrationId.value;

  // 用户最后一次的定位的经纬度个位置
  Rx<UserLocationInfo> userLocationInfo = UserLocationInfo().obs;
  // 获取用户最后一次的定位信息
  UserLocationInfo get userLocation => userLocationInfo.value;

  LoginModel? loginDataModel;
  LoginModel? get loginModel => loginDataModel;

  @override
  void onInit() async {
    super.onInit();
    // String? token = Storage.getString(StorageKeys.storageToken);
    // logs('UserService - 查询SP token：$token');
    // setToken(token);
    // userLocationInfo.value = getLocationInfo();
  }

  void initUser() {
    String? token = Storage.getString(AppStorageKeys.storageToken);
    logs('UserService - 查询SP token：$token');
    setToken(token);
    userLocationInfo.value = getLocationInfo();
  }

  /// 存储登录信息
  void saveLoginModel({required LoginModel login}) {
    String accessToken = '${login.tokenType} ${login.accessToken}';
    setToken(accessToken);
    Map<String, dynamic> loginData = login.toJson();
    Storage.setJsonMap(AppStorageKeys.storageLoginModel, loginData);
    loginDataModel = login;
  }

  /// 设置全局的Token，同时更新haslogin 的值，赋值时机如下
  /*
      1. 在登录或注册成功的时候赋值
      2. 在main.dart中初始化的时候查询是否有Token,如果有的话需要赋值
      3. 退出登录的时候需要赋值
   */
  void setToken(String? token) {
    this.token = token;

    if (token.toString().isEmpty) {
      haslogin.value = false;
      Storage.remove(AppStorageKeys.storageToken);
      Storage.remove(StorageKeys.userToken);
    } else {
      Storage.setString(AppStorageKeys.storageToken, token!);
      Storage.setString(StorageKeys.userToken, token);
      haslogin.value = true;
      fetchUserProfile();
    }

    logs('UserService =========> 设置Token为：$token');
  }

  void removeToken() {
    Storage.remove(AppStorageKeys.storageToken);
    Storage.remove(StorageKeys.userToken);
    Storage.remove(AppStorageKeys.storageLoginModel);
  }

  /// 获取用户最后一次的定位信息
  /// 如果本地有数据，则直接返回，否则返回默认数据
  UserLocationInfo getLocationInfo() {
    try {
      Map<String, dynamic> locationMap = Storage.getJson(AppStorageKeys.storageLocationInfo);
      UserLocationInfo locationInfo = UserLocationInfo.fromJson(locationMap);
      userLocationInfo.value = locationInfo;
      return locationInfo;
    } catch (e) {
      return UserLocationInfo(latitude: '0.0', longitude: '0.0', address: '');
    }
  }

  /// 请求接口获取用户详情
  /// 【getInd=self】时，【indVal】为空串
  /// 【getInd=uid】时，【indVal】为要查询的用户uid
  /// 【getInd=accid】时，【indVal】为要查询的用户accid
  Future<UserProfile?> fetchUserProfile() async {
    if (isLogin) {
      Result result = await HttpProvider.get(
        '/user/getUserInfo',
        params: {'getInd': 'self', 'indVal': ''},
        explain: '获取用户信息',
      );
      if (result.succ) {
        userProfile.value = UserProfile.fromJson(result.data);
        return userProfile.value;
      }
    }
    // 获取用户信息失败
    return null;
  }

  /// description

  /// 更新用户信息back
  /// [nickName] 昵称
  /// [realName] 真实姓名
  /// [avatarId] 头像id
  /// [sex] 性别    1：男，0：女
  /// [birthday] 年龄  2021-1-12
  void updateUserInfo(
      {String? nickName, String? realName, int? avatarId, int? sex, String? birthday, UserInfoBlock? callback}) async {
    Map<String, dynamic> params = {};
    if (nickName != null) {
      params['nick_name'] = nickName;
    }
    if (realName != null) {
      params['real_name'] = realName;
    }
    if (avatarId != null) {
      params['avatar'] = avatarId;
    }
    if (sex != null) {
      params['sex'] = sex;
    }
    if (birthday != null) {
      params['birthday'] = birthday;
    }
    Result result = await HttpProvider.post(
      '/client/user_info',
      params: params,
      explain: '更新用户信息',
    );
    logs(result.toJson());
    if (result.succ) {
      // Toast.showText('修改成功');
      UserProfile? userProfile = await fetchUserProfile();
      if (userProfile != null) {
        this.userProfile.value = userProfile;
        callback?.call(userProfile);
      }
    } else {
      // Toast.showText('修改失败');
    }
  }

  /// 上传用户头像
  void uploadUserAvater({required String filePath, UploadCallback? callBack}) async {
    UploadImage.uploadImage(
        filePath: filePath,
        type: UploadImageType.avatar,
        callBack: (imaheUrl, id) {
          callBack?.call(imaheUrl, id);
        });
  }

  void verifyHasLogin({required Function callback}) {
    if (isLogin) {
      callback();
    } else {
      // LoginUtils.goToLogin();
      // Future.delayed(const Duration(milliseconds: 200), () {
      //   final MineLogic logic = Get.put(MineLogic());
      //   logic.resetData();
      // });
    }
  }

  /// 处理退出登录之后的数据清除
  void logout() {
    Storage.remove(AppStorageKeys.storageToken);
    Storage.remove(AppStorageKeys.storageLocationInfo);
    haslogin.value = false;
    userProfile.value = UserProfile(avatar: '');
  }
}
